/* ====================================================================
 * (#)Header: ComparatorUtils.java
 * (#)Revision: 
 * (#)Date Created: Mar 2, 2007 12:07:22 AM
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.bean;

import java.lang.reflect.Method;

/**
 * <code>ComparatorUtils</code> is used to ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class ComparatorUtils {

	// === public static utility api === //
	public static <T> int compare(T o1, T o2, String... propertyNames) {
		int result = 0;
		if (propertyNames == null || propertyNames.length == 0) {
			return result;
		}
		for (String propertyName : propertyNames) {
			result = compare(o1, o2, propertyName);
			if (result != 0) {
				return result;
			}
		}
		return result;
	}

	public static <T> int compare(T o1, T o2, String propertyName) {
		Object value = BeanUtils.getPropertyValue(o1, propertyName);
		Object value2 = BeanUtils.getPropertyValue(o2, propertyName);
		return compare(value, value2);
	}

	public static <T> int compare(T o1, T o2, Method... propertyAccessors) {
		int result = 0;
		if (propertyAccessors == null || propertyAccessors.length == 0) {
			return result;
		}
		for (Method propertyAccessor : propertyAccessors) {
			result = compare(o1, o2, propertyAccessor);
			if (result != 0) {
				return result;
			}
		}
		return result;
	}

	public static <T> int compare(T o1, T o2, Method propertyAccessor) {
		Object value = BeanUtils.getPropertyValue(o1, propertyAccessor);
		Object value2 = BeanUtils.getPropertyValue(o2, propertyAccessor);
		return compare(value, value2);
	}

	@SuppressWarnings("unchecked")
	public static int compare(Object o1, Object o2) {
		if (o1 == null && o2 == null) {
			return 0;
		}
		if (o1 == null) {
			return -1;
		}
		if (o2 == null) {
			return 1;
		}
		if (o1 instanceof String && o2 instanceof String) {
			String s1 = ((String) o1).trim().toLowerCase();
			String s2 = ((String) o2).trim().toLowerCase();
			return s1.compareTo(s2);
		}

		if (o1 instanceof Comparable && o2 instanceof Comparable) {
			Comparable<Object> c1 = (Comparable<Object>) o1;
			Comparable<Object> c2 = (Comparable<Object>) o2;
			return c1.compareTo(c2);
		}
		return 0;
	}
}
